package com.hgc.ch01.pool;


import java.sql.Connection;
import java.util.LinkedList;

/**
 * Created by 01367627 on 2019/6/27.
 */
public class DBPool {
    private LinkedList<Connection> pool = new LinkedList<Connection>();

    public DBPool(int initialSize) {
        if (initialSize <= 0) {
            throw new IllegalArgumentException("连接池大小必须大于0！");
        }
        for (int i = 0; i < initialSize; i++) {
            pool.addLast(ConnectionFactory.createConnection());
        }
    }

    public void releaseConnection(Connection connection){
        if(connection != null){
            synchronized (pool){
                pool.addLast(connection);
                pool.notifyAll();
            }
        }
    }

    public Connection fetchConnection(Long mills) throws InterruptedException {
        synchronized (pool){
            if(mills <= 0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else{
                long future = System.currentTimeMillis() + mills;
                long remaining = mills;
                while(pool.isEmpty() && remaining > 0){
                    pool.wait(remaining);
                    remaining = future - System.currentTimeMillis();
                }
                Connection connection = null;
                while(!pool.isEmpty()){
                    connection = pool.removeFirst();
                }
                return connection;
            }
        }
    }

}
